<template>
  <div class="growth-box">
    <h1 class="page-title">
      <el-icon class="title-icon"><Box /></el-icon>
      成长盒
    </h1>
    
    <p class="page-description">
      <el-icon class="desc-icon"><MagicStick /></el-icon>
      收纳已掌握的任务，见证孩子成长的每一步印记
    </p>

    <!-- 成长盒任务列表 -->
    <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>
            <el-icon style="margin-right: 8px;"><Trophy /></el-icon>
            已掌握的任务
          </span>
          <span class="task-count">
            <el-icon style="margin-right: 5px;"><DataAnalysis /></el-icon>
            共 {{ growthBoxTasks.length }} 个任务
          </span>
        </div>
      </template>

      <div v-loading="loading" class="task-list">
        <el-empty v-if="growthBoxTasks.length === 0" description="成长盒还是空的，快去收纳已掌握的任务吧！">
          <el-button type="primary" @click="goToTaskLibrary">
            <el-icon style="margin-right: 5px;"><Reading /></el-icon>
            去任务库
          </el-button>
        </el-empty>

        <el-table v-else :data="growthBoxTasks" stripe style="width: 100%">
          <el-table-column prop="title" label="任务名称" min-width="150">
            <template #default="{ row }">
              <div class="task-title">{{ row.title }}</div>
              <div class="task-desc">{{ row.description }}</div>
            </template>
          </el-table-column>

          <el-table-column prop="domain" label="领域" width="150">
            <template #default="{ row }">
              <el-tag :type="getDomainTagType(row.domain)">
                <el-icon style="margin-right: 4px;">
                  <component :is="getDomainIcon(row.domain)" />
                </el-icon>
                {{ getDomainLabel(row.domain) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="difficulty" label="难度" width="120">
            <template #default="{ row }">
              <el-tag :type="getDifficultyTagType(row.difficulty)">
                <el-icon style="margin-right: 4px;">
                  <component :is="getDifficultyIcon(row.difficulty)" />
                </el-icon>
                {{ getDifficultyLabel(row.difficulty) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="addedAt" label="掌握日期" width="180" align="center">
            <template #default="{ row }">
              {{ formatDateTime(row.addedAt) }}
            </template>
          </el-table-column>

          <el-table-column prop="note" label="备注" min-width="150" show-overflow-tooltip>
            <template #default="{ row }">
              <span class="note-text">{{ row.note || '无' }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="160" fixed="right" align="center">
            <template #default="{ row }">
              <el-button
                type="danger"
                link
                size="small"
                @click="handleRemove(row)"
              >
                <el-icon style="margin-right: 5px;"><Delete /></el-icon>
                移出成长盒
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 成长历程 -->
    <el-card class="content-card milestone-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>
            <el-icon style="margin-right: 8px;"><TrophyBase /></el-icon>
            成长历程
          </span>
          <span class="task-count">
            <el-icon style="margin-right: 5px;"><Odometer /></el-icon>
            {{ growthBoxTasks.length }} 个里程碑
          </span>
        </div>
      </template>

      <div class="milestone-container">
        <el-empty v-if="growthBoxTasks.length === 0" description="还没有成长记录" />
        
        <div v-else class="milestone-timeline">
          <!-- 中央时间线 -->
          <div class="timeline-line"></div>
          
          <div
            v-for="(task, index) in sortedTasks"
            :key="task.id"
            class="milestone-item-wrapper"
            :class="{ 'left-side': index % 2 === 0, 'right-side': index % 2 !== 0 }"
            :style="{ animationDelay: `${index * 0.1}s` }"
          >
            <!-- 左侧内容 (偶数索引) -->
            <div class="milestone-content-left">
              <div v-if="index % 2 === 0" class="task-box" :style="{ borderColor: getBorderColor(task.domain) }">
                <h3 class="milestone-title-text">{{ task.title }}</h3>
                <p class="milestone-description-text">{{ task.description }}</p>
              </div>
            </div>

            <!-- 中央圆点和时间标签 -->
            <div class="timeline-center">
              <div class="timeline-dot-wrapper">
                <div class="timeline-dot" :style="{ background: getIconGradient(task.domain) }"></div>
                <div class="timeline-date-label">{{ formatDate(task.addedAt) }}</div>
              </div>
            </div>

            <!-- 右侧内容 (奇数索引) -->
            <div class="milestone-content-right">
              <div v-if="index % 2 !== 0" class="task-box" :style="{ borderColor: getBorderColor(task.domain) }">
                <h3 class="milestone-title-text">{{ task.title }}</h3>
                <p class="milestone-description-text">{{ task.description }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Box, 
  MagicStick, 
  Trophy, 
  TrophyBase, 
  DataAnalysis, 
  Odometer, 
  Delete, 
  Reading,
  User,
  Sunny,
  FirstAidKit,
  ChatDotRound,
  MagicStick as CognitionIcon,
  Operation,
  Star,
  StarFilled,
  SemiSelect
} from '@element-plus/icons-vue'
import { getGrowthBoxTasks, removeFromGrowthBox } from '@/api/growthBox'
import { DOMAIN_MAP, DIFFICULTY_MAP } from '@/utils/constants'

const router = useRouter()

const loading = ref(false)
const growthBoxTasks = ref([])

// 按时间倒序排列的任务（最新的在前面）
const sortedTasks = computed(() => {
  return [...growthBoxTasks.value].sort((a, b) => {
    return new Date(b.addedAt) - new Date(a.addedAt)
  })
})

// 加载成长盒任务
const loadGrowthBoxTasks = async () => {
  loading.value = true
  try {
    const response = await getGrowthBoxTasks()
    if (response.code === 200) {
      growthBoxTasks.value = response.data || []
    } else {
      ElMessage.error(response.message || '加载成长盒任务失败')
    }
  } catch (error) {
    console.error('加载成长盒任务失败:', error)
    ElMessage.error('加载成长盒任务失败')
  } finally {
    loading.value = false
  }
}

// 移除任务
const handleRemove = async (task) => {
  try {
    await ElMessageBox.confirm(
      `确定要将"${task.title}"移出成长盒吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await removeFromGrowthBox(task.id)
    if (response.code === 200) {
      ElMessage.success('已移出成长盒')
      loadGrowthBoxTasks()
    } else {
      ElMessage.error(response.message || '移出失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移出任务失败:', error)
      ElMessage.error('移出任务失败')
    }
  }
}

// 前往任务库
const goToTaskLibrary = () => {
  router.push('/app/task-library')
}

// 获取领域标签类型
const getDomainTagType = (domain) => {
  const types = {
    social: '',
    emotion: 'success',
    selfcare: 'warning',
    cognition: 'danger',
    behavior: 'info',
    sensory: ''
  }
  return types[domain] || ''
}

// 获取领域标签文本
const getDomainLabel = (domain) => {
  return DOMAIN_MAP[domain] || domain
}

// 获取领域图标
const getDomainIcon = (domain) => {
  const icons = {
    social: User,
    emotion: Sunny,
    selfcare: FirstAidKit,
    communication: ChatDotRound,
    cognition: CognitionIcon,
    motor: Operation
  }
  return icons[domain] || User
}

// 获取难度标签类型
const getDifficultyTagType = (difficulty) => {
  const types = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return types[difficulty] || ''
}

// 获取难度标签文本
const getDifficultyLabel = (difficulty) => {
  return DIFFICULTY_MAP[difficulty] || difficulty
}

// 获取难度图标
const getDifficultyIcon = (difficulty) => {
  const icons = {
    1: Star,
    2: StarFilled,
    3: SemiSelect
  }
  return icons[difficulty] || Star
}

// 获取图标渐变色（用于时间线圆点）
const getIconGradient = (domain) => {
  const gradients = {
    social: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    emotion: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    selfcare: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    cognition: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    behavior: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    sensory: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)'
  }
  return gradients[domain] || 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)'
}

// 获取任务框边框颜色
const getBorderColor = (domain) => {
  const colors = {
    social: '#667eea',
    emotion: '#f093fb',
    selfcare: '#4facfe',
    cognition: '#43e97b',
    behavior: '#fa709a',
    sensory: '#30cfd0'
  }
  return colors[domain] || '#d0d0d0'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 格式化日期
const formatDate = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

onMounted(() => {
  loadGrowthBoxTasks()
})
</script>

<style scoped>
.growth-box {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 28px;
  color: #8b5cf6;
}

.page-description {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
  line-height: 1.6;
  display: flex;
  align-items: center;
  gap: 6px;
}

.desc-icon {
  font-size: 16px;
  color: #ec4899;
}

.content-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.task-count,
.record-count {
  font-size: 14px;
  color: #999;
  font-weight: normal;
}

.task-list {
  min-height: 200px;
}

.task-title {
  font-weight: bold;
  margin-bottom: 4px;
}

.task-desc {
  font-size: 12px;
  color: #999;
}

.note-text {
  color: #666;
  font-size: 13px;
}

/* 成长历程样式 */
.milestone-card {
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f0 100%);
  border: none;
}

.milestone-container {
  padding: 30px 20px;
}

.milestone-timeline {
  position: relative;
  padding: 40px 0;
  max-width: 1000px;
  margin: 0 auto;
}

/* 中央时间线 */
.timeline-line {
  position: absolute;
  left: 50%;
  top: 0;
  bottom: 0;
  width: 2px;
  background: linear-gradient(
    to bottom,
    #e0e0e0,
    #d0d0d0,
    #e0e0e0
  );
  transform: translateX(-50%);
  z-index: 0;
}

.milestone-item-wrapper {
  position: relative;
  display: grid;
  grid-template-columns: 1fr 0px 1fr;
  gap: 0;
  margin-bottom: 60px;
  animation: fadeInUp 0.6s ease-out forwards;
  opacity: 0;
  z-index: 1;
}

.milestone-item-wrapper.left-side {
  animation: fadeInLeft 0.6s ease-out forwards;
}

.milestone-item-wrapper.right-side {
  animation: fadeInRight 0.6s ease-out forwards;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInLeft {
  from {
    opacity: 0;
    transform: translateX(-30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes fadeInRight {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 中央时间线区域 */
.timeline-center {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  z-index: 2;
  top: 0;
}

/* 时间线圆点包装 */
.timeline-dot-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

/* 时间线圆点 */
.timeline-dot {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  border: 4px solid white;
  box-shadow: 0 0 0 2px #d0d0d0, 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.timeline-dot:hover {
  transform: scale(1.2);
  box-shadow: 0 0 0 3px #b0b0b0, 0 4px 16px rgba(0, 0, 0, 0.25);
}

/* 时间线日期标签 */
.timeline-date-label {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 13px;
  font-weight: 600;
  padding: 6px 12px;
  border-radius: 20px;
  white-space: nowrap;
  box-shadow: 0 3px 10px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  letter-spacing: 0.5px;
}

.timeline-date-label:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

/* 左侧内容 */
.milestone-content-left {
  text-align: right;
  padding-right: 40px;
}

/* 右侧内容 */
.milestone-content-right {
  text-align: left;
  padding-left: 40px;
}

/* 任务框 */
.task-box {
  border: 3px solid;
  border-radius: 12px;
  padding: 20px 24px;
  background: white;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  text-align: left;
  min-width: 300px;
  word-wrap: break-word;
  white-space: normal;
}

.task-box:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

/* 标题样式 */
.milestone-title-text {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 0 0 12px 0;
  line-height: 1.4;
}

/* 描述样式 */
.milestone-description-text {
  font-size: 15px;
  color: #666;
  line-height: 1.8;
  margin: 0;
}


/* 响应式布局 */
@media (max-width: 992px) {
  .milestone-timeline {
    padding: 30px 10px;
    max-width: 100%;
  }

  .milestone-item-wrapper {
    grid-template-columns: 1fr;
    gap: 15px;
    margin-bottom: 50px;
  }

  .timeline-line {
    left: 30px;
  }

  .timeline-dot {
    width: 14px;
    height: 14px;
    border: 3px solid white;
  }

  .timeline-date-label {
    font-size: 12px;
    padding: 5px 10px;
  }

  .milestone-content-left,
  .milestone-content-right {
    margin-left: 80px;
    text-align: left;
    padding: 0 0 0 20px;
  }

  .timeline-center {
    left: 30px;
    transform: none;
  }

  .task-box {
    border-width: 2px;
    padding: 16px 20px;
    min-width: 250px;
  }

  .milestone-title-text {
    font-size: 18px;
  }

  .milestone-description-text {
    font-size: 14px;
  }
}

@media (max-width: 768px) {
  .growth-box {
    padding: 10px;
  }

  .page-title {
    font-size: 20px;
  }

  .milestone-container {
    padding: 20px 10px;
  }

  .milestone-timeline {
    padding: 20px 0;
  }

  .timeline-line {
    left: 20px;
  }

  .timeline-dot {
    width: 12px;
    height: 12px;
    border: 2px solid white;
  }

  .timeline-date-label {
    font-size: 11px;
    padding: 4px 8px;
  }

  .milestone-content-left,
  .milestone-content-right {
    margin-left: 70px;
    padding: 0 0 0 15px;
  }

  .timeline-center {
    left: 20px;
    transform: none;
  }

  .task-box {
    border-width: 2px;
    padding: 14px 18px;
    border-radius: 10px;
    min-width: 200px;
  }

  .milestone-title-text {
    font-size: 17px;
  }

  .milestone-description-text {
    font-size: 13px;
  }
}
</style>
